package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.BootstrapText;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.infore.airsupervise.R;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.LawingSiteE;
import com.infore.airsupervise.bean.MissionE;
import com.infore.airsupervise.bean.MissionHandleE;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.MissionBiz;
import com.infore.airsupervise.biz.impl.MissionBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.other.listener.LayoutControl;
import com.infore.airsupervise.other.listener.LayoutControlListener;
import com.infore.airsupervise.ui.fragment.MissionFileShowFragment;
import com.infore.airsupervise.ui.fragment.MissionProcessFragment;
import com.infore.airsupervise.ui.widget.ItemDecoration1px;
import com.infore.airsupervise.utils.JumpUtil;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * @features:
 * @author: WuTao
 * @date: 2017/5/9 16:48
 */
public class NewMissionDetailActivity extends BaseTitleBarActivity {

    @BindView(R.id.tv_mission_title)
    TextView tvTitle;
    @BindView(R.id.tv_mission_discrib)
    TextView tvDiscrib;
    @BindView(R.id.tv_detail_arrow)
    AwesomeTextView tvDetailArrow;
    @BindView(R.id.tv_mission_leader)
    TextView tvLeader;
    @BindView(R.id.tv_mission_handle_other)
    TextView tvHandleOther;
    @BindView(R.id.tv_mission_issue_time)
    TextView tvIssueTime;
    @BindView(R.id.tv_mission_deadline)
    TextView tvDeadline;
    @BindView(R.id.ll_mission_detail)
    LinearLayout llDetail;
    @BindView(R.id.tv_process_arrow)
    AwesomeTextView tvProcessArrow;
    @BindView(R.id.fl_mission_process)
    FrameLayout flProcess;
    @BindView(R.id.tv_file_arrow)
    AwesomeTextView tvFileArrow;
    @BindView(R.id.fl_mission_file)
    FrameLayout flFile;
    @BindView(R.id.tv_law_site_arrow)
    AwesomeTextView tvLawSiteArrow;
    @BindView(R.id.ll_law_site_control)
    LinearLayout llLawSiteControl;
    @BindView(R.id.rv_mission_law_site)
    RecyclerView rvLawSite;


    private MissionBiz missionBiz;
    private MissionE missionE;

    private MissionProcessFragment processFragment;
    private MissionFileShowFragment fileFragment;
    private String userId;//当前用户的id
    private List<MissionE.MissionProcess> data_progress = new ArrayList<>();
    private  BaseQuickAdapter<LawingSiteE,BaseViewHolder> adapter ;
    private List<LawingSiteE> data_siteLaw = new ArrayList<>();
    private List<String> file_list ;

    private LayoutControlListener layoutControl; //布局UI控制


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_law_mission);
        getWindow().setBackgroundDrawable(null);
        ButterKnife.bind(this);
        title.setText("任务信息");
        rightMenu.setVisibility(View.GONE);
        userId = UserE.getUserInfo().getUserId();
        missionBiz = new MissionBizImpl();
        layoutControl =  new LayoutControl(ctx);
        try {
            Intent it = getIntent();
            missionE = (MissionE) it.getSerializableExtra(Constants.INTENT_OBJ_KEY);
            initView();
        } catch (Exception ex) {
            ToastUtil.showShort(ctx, "异常");
        }
    }

    /**
     * 初始化任务信息
     */
    private void initView() {
        tvTitle.setText(missionE.getTitle());
        tvDiscrib.setText(missionE.getDiscrib());
        tvLeader.setText(missionE.getLeaderName());
        tvIssueTime.setText(missionE.getIssueTime());
        tvDeadline.setText(missionE.getLastTime());
        //流程部分
        processFragment = new MissionProcessFragment(data_progress, missionE.getIssueTime(), missionE.getLeaderName());
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_mission_process, processFragment).commit();
        //获取流程
        getProcessData();

        file_list = new ArrayList<>();
        //录音附件
        if(null != missionE.getVoice()){
            file_list.addAll(missionE.getVoice());
        }
        //其他附件
        if(null !=  missionE.getFile()){
            file_list.addAll( missionE.getFile());
        }
        fileFragment = new MissionFileShowFragment(file_list);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_mission_file, fileFragment).commit();
        initRecyclerView();
    }

    /**
     * 初始化执法记录列表
     */
    private void initRecyclerView(){
        rvLawSite.setLayoutManager( new LinearLayoutManager(ctx));
        ItemDecoration1px itemDecoration = new ItemDecoration1px(ctx , ItemDecoration1px.VERTICAL_LIST);
        rvLawSite.addItemDecoration(itemDecoration);
        adapter = new BaseQuickAdapter<LawingSiteE, BaseViewHolder>(R.layout.item_mission_mune ,data_siteLaw) {
            @Override
            protected void convert(BaseViewHolder helper, LawingSiteE item) {
                helper.setText(R.id.tv_mission_menu,"现场检查记录");
            }
        };
        rvLawSite.setAdapter(adapter);
        rvLawSite.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                JumpUtil.jumpFromTo(ctx,SiteMainDetailActivity.class,Constants.INTENT_OBJ_KEY,adapter.getItem(position));

            }
        });
    }


    /**
     * 根据任务状态控制布局显示
     *
     * @param missionStatus
     */
    private void MissionStatusLayoutControl(int missionStatus) {
        switch (missionStatus) {
            case StatusConst.MISSION_PROCESS_1: //待办
                if (TextUtils.equals(userId, missionE.getLeaderId())) {
                    rightMenu.setBootstrapText(
                            new BootstrapText.Builder(ctx).addText("处理").build());
                    rightMenu.setVisibility(View.VISIBLE);
                }
                break;
            case StatusConst.MISSION_PROCESS_5: //需要我审核的
                if (missionE.getIsApproved() == 1 &&
                        TextUtils.equals(userId, missionE.getApprovePson())) {
                    rightMenu.setBootstrapText(
                            new BootstrapText.Builder(ctx).addText("审核").build());
                    rightMenu.setVisibility(View.VISIBLE);
                }
                break;
            default:
                rightMenu.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 获取流程
     */
    private void getProcessData() {
        //loading dialog
        final SweetAlertDialog dialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText(MsgConst.PLEASE_WAITING);
        dialog.setCancelable(false);
        dialog.show();
        missionBiz.sendMissionProcessRequest(missionE.getId(), new OnServerResponseListener<MissionHandleE>() {
            @Override
            public void onSucceed(MissionHandleE result, String desc) {
                dialog.dismiss();
                if (null != result ) {
                    if(null != result.getProcessList()) {
                        data_progress.clear();
                        data_progress.addAll(result.getProcessList());
                        processFragment.update();
                        MissionStatusLayoutControl(processFragment.getLastStatus());
                    }
                    if(null != result.getTzList()){
                        data_siteLaw.clear();
                        data_siteLaw.addAll(result.getTzList());
                        adapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                //失败提示dialog
                dialog.setTitleText(title)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.WARNING_TYPE);
            }
        });
    }
    /**
     * 布局控制
     */
    private boolean isDetailShowed = false;
    private boolean isProcessShowed = true;
    private boolean isFileShowed = true;
    private boolean isSiteShowed = true;
    @OnClick({R.id.ll_detail_control, R.id.ll_process_control, R.id.ll_file_control, R.id.ll_law_site_control})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_detail_control:
                isDetailShowed = !isDetailShowed;
                layoutControl.layoutControl(isDetailShowed, llDetail, tvDetailArrow);
                break;
            case R.id.ll_process_control:
                isProcessShowed = !isProcessShowed;
                layoutControl.layoutControl(isProcessShowed, flProcess, tvProcessArrow);
                break;
            case R.id.ll_file_control:
                isFileShowed = !isFileShowed;
                layoutControl.layoutControl(isFileShowed, flFile, tvFileArrow);
                break;
            case R.id.ll_law_site_control:
                isSiteShowed = !isSiteShowed;
                layoutControl.layoutControl(isSiteShowed, rvLawSite, tvLawSiteArrow);
                break;
        }
    }

    @Override
    protected void onRightMenuClick(View view) {
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.INTENT_INT_KEY,processFragment.getLastStatus());
        bundle.putString(Constants.INTENT_STR_KEY, missionE.getId());
        JumpUtil.ForResultJumpFromTo(this, NewMissionHandleActivity.class, bundle, 500);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 500 && resultCode == RESULT_OK) {
            //从handle界面回来 刷新流程 和 界面 任务状态
            getProcessData();
//            int status = data.getIntExtra(Constants.INTENT_INT_KEY, -1);
//            missionE.setMissionStatus(status);
//            MissionStatusLayoutControl(status);
        }
    }
}
